<?php
namespace App\Job;

use Hyperf\AsyncQueue\Job;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use App\Service\ArticleService;
use App\Helper\SeoHelper;

class ArticleJob extends Job
{
    protected $productId;
    protected $getData;
    protected $logger;

    /**
     * @var ArticleService
     */
    protected $articleService;

    public function __construct(int $productId, array $getData, LoggerFactory $loggerFactory)
    {
        $this->productId = $productId;
        $this->getData = $getData;
        $this->logger = $loggerFactory->get('article', 'article');
    }

    public function handle()
    {
        try {
            $webname = $this->getData['webname'] ?? '';
            $articleKeywords = trim($this->getData['keywords'] ?? '');
            $extensions = trim($this->getData['extensions'] ?? '');

            if (empty($webname)) {
                $this->logger->warning("webname为空，跳过任务", [
                    'product_id' => $this->productId
                ]);
                return;
            }

            $conn = Db::connection($webname);
            $product = $conn->selectOne("
                SELECT 
                    p.product_id, 
                    pd.name AS product_name, 
                    p.image, 
                    pd.tag, 
                    pd.description, 
                    pd.meta_title, 
                    pd.meta_description 
                FROM oc_product p 
                JOIN oc_product_description pd 
                    ON p.product_id = pd.product_id 
                WHERE p.product_id = :pid LIMIT 1",
                ['pid' => $this->productId]
            );

            if (!$product) {
                $this->logger->warning("未找到产品", [
                    'product_id' => $this->productId,
                    'webname' => $webname
                ]);
                return;
            }

            $this->logger->info("找到产品", [
                'product_id' => $product->product_id,
                'product_name' => $product->product_name,
                'webname' => $webname
            ]);

            $productImageUrl = "https://www.".filter_var($webname, FILTER_SANITIZE_URL).".com/image/".filter_var($product->image, FILTER_SANITIZE_URL);

            $articleService = ApplicationContext::getContainer()->get(ArticleService::class);

            $article = $articleService->generateArticle([
                'name' => $product->product_name,
                'description' => strip_tags(html_entity_decode($product->description)),
                'meta_title' => $product->meta_title,
                'meta_description' => $product->meta_description,
                'tags' => $product->tag,
                'keywords' => $articleKeywords,
                'extensions' => $extensions,
                'webname' => $webname,
                'images' => $productImageUrl,
                'url' => "https://www.".filter_var($webname, FILTER_SANITIZE_URL).".com/index.php?route=product/product&product_id=".filter_var($product->product_id, FILTER_SANITIZE_NUMBER_INT)
            ]);

            if (!is_array($article) || empty($article['post_title'])) {
                $this->logger->warning("AI返回文章为空", [
                    'product_id' => $this->productId,
                    'webname' => $webname
                ]);
                return;
            }

            $conn->beginTransaction();

            try {
                $bm_post_image = filter_var($product->image, FILTER_SANITIZE_URL);
                $bm_post_viewed = rand(20,123);

                $conn->insert("
                        INSERT INTO oc_bm_post 
                            (user_id, image, image_title, image_alt, review_display, images_review, viewed, status, 
                            limit_access_user, limit_users, limit_access_user_group, limit_user_groups, custom, setting, 
                            date_added, date_published, date_modified) 
                        VALUES 
                            (:user_id, :image, :image_title, :image_alt, :review_display, :images_review, :viewed, :status, 
                            :limit_access_user, :limit_users, :limit_access_user_group, :limit_user_groups, :custom, :setting, 
                            NOW(), NOW(), NOW())
                    ", [
                    'user_id' => 1,
                    'image' => $bm_post_image,
                    'image_title' => $product->product_name,
                    'image_alt' => $product->product_name,
                    'review_display' => 0,
                    'images_review' => 0,
                    'viewed' => $bm_post_viewed,
                    'status' => 1,
                    'limit_access_user' => 0,
                    'limit_users' => '',
                    'limit_access_user_group' => 0,
                    'limit_user_groups' => '',
                    'custom' => 0,
                    'setting' => ''
                ]);

                $postId = $conn->getPdo()->lastInsertId();
                $post_title = trim($article['post_title']);
                $short_description = trim($article['short_description']);

                $description = preg_replace('/\s+/', ' ', trim($article['description']));
                $description = preg_replace('/\s*(<[^>]+>)\s*/', '$1', $description);

                $meta_tag_title = trim($article['meta_tag_title']);
                $meta_tag_description = trim($article['meta_tag_description']);
                $meta_keywords = !empty($article['meta_keywords']) ? trim($article['meta_keywords']) : '';
                $tags = !empty($article['tags']) ? trim($article['tags']) : '';

                $conn->insert("
                        INSERT INTO oc_bm_post_description 
                            (post_id, language_id, title, short_description, description, meta_title, meta_description, meta_keyword, tag) 
                        VALUES 
                            (:post_id, :language_id, :title, :short_description, :description, :meta_title, :meta_description, :meta_keyword, :tag)
                    ", [
                    'post_id' => $postId,
                    'language_id' => 1,
                    'title' => $post_title,
                    'short_description' => $short_description,
                    'description' => $description,
                    'meta_title' => $meta_tag_title,
                    'meta_description' => $meta_tag_description,
                    'meta_keyword' => $meta_keywords,
                    'tag' => $tags
                ]);

                $conn->insert("INSERT INTO oc_bm_post_to_store (post_id, store_id) VALUES (:post_id, :store_id)", ['post_id' => $postId, 'store_id' => 0]);

                //post_category
                // 获取商品分类信息
                $productCategories = $conn->select("SELECT c.category_id, cd.name 
                                                FROM oc_product_to_category c
                                                LEFT JOIN oc_category_description cd ON c.category_id = cd.category_id AND cd.language_id = 1
                                                WHERE c.product_id = :product_id
                                            ", ['product_id' => $this->productId]);

                $postCategoryIds = [];
                if (!empty($productCategories)) {
                    foreach ($productCategories as $category) {
                        $catName = $category->name;

                        $bmCategory = $conn->selectOne("SELECT category_id FROM oc_bm_category_description WHERE title = :title AND language_id = 1", ['title' => $catName]);

                        if ($bmCategory) {
                            $postCategoryIds[] = $bmCategory->category_id;
                        }
                    }
                }

                if (empty($postCategoryIds)) {
                    $postCategoryIds[] = 27;
                }

                foreach ($postCategoryIds as $catId) {
                    $conn->insert("INSERT INTO oc_bm_post_to_category (post_id, category_id) VALUES (:post_id, :category_id)", ['post_id' => $postId, 'category_id' => $catId]);
                }

                $conn->insert("INSERT INTO oc_bm_post_to_product (post_id, product_id)  VALUES (:post_id, :product_id)", ['post_id' => $postId, 'product_id' => $this->productId]);

                $conn->insert("INSERT INTO oc_bm_post_to_layout (post_id, store_id, layout_id)  VALUES (:post_id, :store_id, :layout_id)", ['post_id' => $postId, 'store_id' => 0, 'layout_id' => 0]);

                $seoUrl = SeoHelper::generateSeoUrl($article['post_title']);
                $conn->insert("INSERT INTO oc_url_absolute (query, redirect, language_id) VALUES (:query, :redirect, :language_id)", [
                    'query' => 'extension/d_blog_module/post&post_id='.$postId,
                    'redirect' => 'blog/'.$seoUrl.'-'.$postId,
                    'language_id' => 1
                ]);

                $conn->commit();

                $this->logger->info("文章生成成功", [
                    'product_id' => $this->productId,
                    'blog_id' => $postId,
                    'webname' => $webname
                ]);

            } catch (\Throwable $e) {
                $conn->rollBack();
                throw $e;
            }

        } catch (\Throwable $e) {
            $this->logger->error("任务处理失败", [
                'product_id' => $this->productId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            throw $e;
        }
    }
}
